package com.example.test.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.Document;

/**
 * word 转换成html  
 * 老版本,已弃用
 */
public class WordToHtmlUtil {

	/**
	 * 2007版本word转换成html
	 * @throws IOException
	 */
	public static String Word2007ToHtml(MultipartFile f) {
		//转化为file对象
		File file = MultipartFileToFile.multipartFileToFile(f);
		String filepath = "G:\\上传测试\\";
//		String fileName = "123.docx";
		String htmlName = "789.html";
//		final String file = filepath + fileName;
//		File f = new File(file);
		if (!file.exists()) {
			System.out.println("Sorry File does not Exists!");
		} else {
			if (file.getName().endsWith(".docx") || file.getName().endsWith(".DOCX")) {
				try {
					// 1) 加载word文档生成 XWPFDocument对象  
					InputStream in = new FileInputStream(file);
					XWPFDocument document = new XWPFDocument(in);

					// 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
					File imageFolderFile = new File(filepath);
					XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
					options.setExtractor(new FileImageExtractor(imageFolderFile));
					options.setIgnoreStylesIfUnused(false);
					options.setFragment(true);

					// 3) 将 XWPFDocument转换成XHTML  
					OutputStream out = new FileOutputStream(new File(filepath + htmlName));
					XHTMLConverter.getInstance().convert(document, out, options);

					//也可以使用字符数组流获取解析的内容
//                ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
//                XHTMLConverter.getInstance().convert(document, baos, options);  
//                String content = baos.toString();
//                System.out.println(content);
//                 baos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			} else {
				System.out.println("Enter only MS Office 2007+ files");
			}
		}
		//删除项目目录下临时文件
		String s = deleteTempFile(file.getName());
		return filepath+htmlName+" 临时文件"+s;
	}

	/**
	 * /**
	 * 2003版本word转换成html
	 * @throws IOException
	 * @throws TransformerException
	 * @throws ParserConfigurationException
	 */
	public static String Word2003ToHtml(MultipartFile f) {
		//转化为file对象
		File file = MultipartFileToFile.multipartFileToFile(f);
		final String imagepath = "G:\\上传测试\\word\\media\\";//解析时候如果doc文件中有图片  图片会保存在此路径
		String filepath = "G:\\上传测试\\";
//		String fileName = "123.doc";
		String htmlName = "456.html";
//		final String file = filepath + fileName;
		OutputStream outStream = null;
		try {
			InputStream input = new FileInputStream(file);
			HWPFDocument wordDocument = new HWPFDocument(input);
			WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
			//设置图片存放的位置
			wordToHtmlConverter.setPicturesManager(new PicturesManager() {
				public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
					File imgPath = new File(imagepath);
					if(!imgPath.exists()){//图片目录不存在则创建
						imgPath.mkdirs();
					}
					File file = new File(imagepath + suggestedName);
					try {
						OutputStream os = new FileOutputStream(file);
						os.write(content);
						os.close();
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
					return imagepath + suggestedName;
				}
			});

			//解析word文档
			wordToHtmlConverter.processDocument(wordDocument);
			Document htmlDocument = wordToHtmlConverter.getDocument();

			File htmlFile = new File(filepath + htmlName);
			outStream = new FileOutputStream(htmlFile);

			//也可以使用字符数组流获取解析的内容
//        ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
//        OutputStream outStream = new BufferedOutputStream(baos);

			DOMSource domSource = new DOMSource(htmlDocument);
			StreamResult streamResult = new StreamResult(outStream);

			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer serializer = factory.newTransformer();
			serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.setOutputProperty(OutputKeys.METHOD, "html");

			serializer.transform(domSource, streamResult);

			//也可以使用字符数组流获取解析的内容
//        String content = baos.toString();
//        System.out.println(content);
//        baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
		try {
			outStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//删除项目目录下临时文件
		String s = deleteTempFile(file.getName());
		return filepath+htmlName+" 临时文件"+s;
	}

	/**
	* @Author: 林文峰 删除项目目录下临时文件
	* @Date 2020/6/19 0019 14:08
	*/
	public static String deleteTempFile(String fileName){
		String result = null;
		File file = new File("");
		try {
			String projectPath = file.getCanonicalPath();
			File deleteFile = new File(projectPath + "/" + fileName);
			if (deleteFile.exists()) {
				if (!deleteFile.isDirectory()){
					boolean delete = deleteFile.delete();
					if (delete){
						result = "删除成功";
					}else {
						result = "删除失败";
					}
				}
			} 
		} catch (IOException e) {
			e.printStackTrace();
			return "io异常";
		}
		return result;
	}
}